package com.xiguaji.tiktok.v1.web.ins;

import com.xiguaji.boot.toolkit.jdbc.Page;
import com.xiguaji.tiktok.v1.ins.favorite.dto.FavoriteTypeEnum;
import com.xiguaji.tiktok.v1.ins.favorite.model.InsFavorite;
import com.xiguaji.tiktok.v1.ins.favorite.service.InsFavoriteService;
import com.xiguaji.tiktok.v1.ins.media.dto.InsMediaData;
import com.xiguaji.tiktok.v1.ins.media.dto.InsMediaSearchRequest;
import com.xiguaji.tiktok.v1.ins.media.service.InsMediaService;
import com.xiguaji.tiktok.v1.web.Tab;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
public class InsPostsController extends InsBaseController {

    @Autowired
    InsMediaService insMediaService;
    @Autowired
    InsFavoriteService insFavoriteService;

    /**
     * 热门广告贴子搜索
     * @return
     */
    @RequestMapping(value = "/hot-instagram-posts",method = RequestMethod.GET)
    public ModelAndView search(){
        ModelAndView modelAndView = getModel(Tab.INS_AD_POSTS_SEARCH.getValue());
        InsMediaSearchRequest insMediaSearchRequest = new InsMediaSearchRequest();
        insMediaSearchRequest.setMediaAdType(1);
        insMediaSearchRequest.setSort(1);
        Page<InsMediaData> insMediaPage = insMediaService.findByPage(insMediaSearchRequest);

        if(null != getUser()){
            insMediaPage.getList().forEach( media ->{
                InsFavorite insFavorite = insFavoriteService.getByTypeAndTargetIdAndUserId(FavoriteTypeEnum.INS_MEDIA.getCode(),media.getId(),(int)getUser().getId());

                if(null != insFavorite) {
                    media.setCollectId(insFavorite.getId());
                }
            });
        }
        modelAndView.addObject("listData",insMediaPage);
        modelAndView.addObject("year", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy")));
        modelAndView.setViewName("ins/media/ad/index");
        return modelAndView;
    }
}
